<template>
  <div class="notice-management">
    <!-- 操作栏 -->
    <!-- 顶部区域 -->
    <div class="operation-bar">
      <el-button type="primary" @click="showADialog" color="#00a2ff">
        <img src="../../assets//icons/releasing.svg" alt="icon" style="width: 18px; height: 18px; margin-right: 8px;" />
        发布新通知
      </el-button>
    </div>


    <!-- 通知列表 -->
    <div class="notice-list">
      <el-card v-for="item in noticeArray" :key="item.id" class="notice-card" shadow="hover">
        <div class="card-header">
          <h3 class="notice-title">{{ item.title }}</h3>
          <div class="operation-buttons">
            <el-button type="primary" size="large" color="#009475"
              @click="showUDialog(item.id, item.title, item.content)">
              <img src="../../assets/icons/edit.svg" alt="icon" style="width: 18px; height: 18px; margin-right: 8px;" />
              编辑
            </el-button>
            <!-- <el-button type="danger" size="large" @click="deleteNotice(item.id)"> -->
            <el-button type="danger" size="large" @click="deleteNotice(item.id)">
              <img src="../../assets/icons/delete.svg" alt="icon"
                style="width: 18px; height: 18px; margin-right: 8px;" />
              删除
            </el-button>
          </div>
        </div>

        <div class="notice-content">{{ item.content }}</div>

        <div class="card-footer">
          <span class="notice-time">
            {{ formatDateTime(item.updatedAt) }}
          </span>
        </div>
      </el-card>
    </div>

    <!-- 底部分页 -->
    <div class="pagination-wrapper">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 编辑/新增弹窗 -->
    <el-dialog v-model="dialogVisible" :title="flag === 0 ? '发布新通知' : '编辑通知'" width="600px">
      <el-form label-width="80px">
        <el-form-item label="通知标题">
          <el-input v-model="title" placeholder="请输入通知标题" />
        </el-form-item>

        <el-form-item label="通知内容">
          <el-input v-model="content" type="textarea" :rows="6" placeholder="请输入通知内容" resize="none" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="flag === 0 ? addNotice() : updateNotice()">
            {{ flag === 0 ? '立即发布' : '确认修改' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, markRaw } from "vue"
import type { ComponentSize } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Warning as ElIconWarning } from '@element-plus/icons-vue' // 导入警告图标
import { listNotice, addNotice as apiAddNotice, updateNotice as apiUpdateNotice, deleteNotice as apiDeleteNotice } from "@/api/Mmp/notice";

// 分页展示相关数据
const size = ref<ComponentSize>('default')
const currentPage = ref(1)
const pageSize = ref(5)
let total = ref(10)

// 弹出框相关数据
let dialogVisible = ref(false)


// 通知数组
let noticeArray = ref([])

// 新增通知相关数据
let id = ref(0)
let title = ref("")
let content = ref("")

// 定义“更改” 和“新增” 标识 更改为0 更新为1 
let flag = ref(0)


function getNotice(page, pageSize) {
  listNotice(page, pageSize).then(result => {
    console.log(result.data)
    noticeArray.value = result.data.records
    total.value = result.data.total
  }).catch(error => {
    console.log(error)
  })
}


// 每页显示条目个数变化
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  getNotice(currentPage.value, val)
}

// 当前页码变化
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  getNotice(val, pageSize.value)
}


// 当组件挂载完毕之后调用函数获取通知信息
onMounted(() => {
  getNotice(currentPage.value, pageSize.value)
})

// 处理时间字符串 去掉其中的字符 "T"
function formatDateTime(dateTimeString) {
  return dateTimeString ? dateTimeString.replace('T', ' ') : '';
}

function addNotice() {
  dialogVisible.value = false
  flag.value = 0
  apiAddNotice(title.value, content.value).then(result => {
    console.log(result)
    getNotice(currentPage.value, pageSize.value)
  }).catch(error => {
    console.log(error)
  })
}



// 显示新增通知弹框 清空之前显示的数据
function showADialog() {
  title.value = ""
  content.value = ""
  dialogVisible.value = true
  flag.value = 0
}

// 显示修改弹框 并显示对应的数据
function showUDialog(noticeId, titleTemp, notice) {
  dialogVisible.value = true
  flag.value = 1

  id.value = noticeId
  title.value = titleTemp
  content.value = notice
}


function updateNotice() {
  dialogVisible.value = false
  apiUpdateNotice(id.value, title.value, content.value).then(result => {
    console.log(result)
    // 修改通知后  获取最新数据
    getNotice(currentPage.value, pageSize.value)
  })
}


async function deleteNotice(noticeId) {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要删除这条通知吗？删除后不可恢复！',
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(ElIconWarning), // 显示警告图标
        buttonSize: 'default',
        customClass: 'delete-confirm-dialog'
      }
    )
    // 用户确认后执行删除
    const result = await apiDeleteNotice(noticeId)
    // 删除成功提示
    ElMessage.success({
      message: '删除成功',
      duration: 2000
    })
    // 删除通知后，获取最新数据
    getNotice(currentPage.value, pageSize.value)

  } catch (error) {
    // 区分用户取消和真实错误
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error({
        message: '删除失败，请稍后重试',
        duration: 2000
      })
    }
  }
}

</script>


<style scoped>
.notice-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
}

.notice-list {
  display: grid;
  gap: 16px;
}

.notice-card {
  margin-bottom: 16px;
  transition: all 0.3s;
}

.notice-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.notice-title {
  margin: 0;
  font-size: 16px;
  color: #303133;
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.operation-buttons {
  flex-shrink: 0;
}

.notice-content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  line-clamp: 3;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

.card-footer {
  border-top: 1px solid #ebeef5;
  padding-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.notice-time {
  font-size: 16px;
  color: #979eac;
}

.pagination-wrapper {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

/* 弹窗样式优化 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
